package mx.kolobok.noteeditor.ui;

import mx.kolobok.noteeditor.NoteManager;
import mx.kolobok.noteeditor.NoteManagerException;
import org.apache.log4j.Logger;
import org.jetbrains.annotations.NonNls;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.prefs.Preferences;

/**
 * Created by IntelliJ IDEA.
 * User: Nikita Belenkiy
 * Date: 28.01.11
 * Time: 23:11
 */
public class MainWindow extends JFrame {

    @NonNls
    private static final String MAIN_WINDOW_WIDTH = "main-window-width";
    @NonNls
    private static final String MAIN_WINDOW_HIGHT = "main-window-hight";
    @NonNls
    private static final String MAIN_WINDOW_X = "main-window-x";
    @NonNls
    private static final String MAIN_WINDOW_Y = "main-window-y";

    @NonNls
    private static final Logger logger = Logger.getLogger(MainWindow.class);


    public MainWindow() throws HeadlessException, NoteManagerException {
        super("Note editor");
        final NoteManager noteManager = NoteManager.createNoteManager();
        final MainForm mf = new MainForm(noteManager);
        addWindowListener(mf);
        setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        add(mf, BorderLayout.CENTER);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final Preferences preferences = Preferences.userNodeForPackage(MainWindow.class);
        setSize(preferences.getInt(MAIN_WINDOW_WIDTH, 400), preferences.getInt(MAIN_WINDOW_HIGHT, 500));
        centerWindowLocation(preferences);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                preferences.putInt(MAIN_WINDOW_WIDTH,getWidth());
                preferences.putInt(MAIN_WINDOW_HIGHT,getHeight());
                preferences.putInt(MAIN_WINDOW_X,getLocationOnScreen().x);
                preferences.putInt(MAIN_WINDOW_Y, getLocationOnScreen().y);
                logger.info("saving main window preferences");

            }
        });

        setVisible(true);
    }

    /**
     * loads location from properties
     * default - center of the screen
     * todo multimonitor env support
     * @param preferences
     */
    private void centerWindowLocation(Preferences preferences) {
        GraphicsEnvironment localGraphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
        Rectangle maximumWindowBounds = localGraphicsEnvironment.getMaximumWindowBounds();
        setLocation(preferences.getInt(MAIN_WINDOW_X, (maximumWindowBounds.width-400)/2), preferences.getInt(MAIN_WINDOW_Y, (maximumWindowBounds.height-500)/2));
    }
}
